<script lang="ts">
import { NTreeSelect } from 'naive-ui'
import { defineComponent, h, shallowRef, onMounted } from 'vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { DicTreeModel } from '@/api/dic'

export default defineComponent({
  name: 'CollectionMethodSelect',
  props: {} as any,
  emits: ['update:value', 'updateValue'],
  setup(props, { emit }) {
    const options = shallowRef<DicTreeModel[]>([])
    const loading = shallowRef(false)

    const queryOptions = async () => {
      loading.value = true

      try {
        const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
          module: 'dic',
          api: 'getTree',
          override: {
            params: {
              dicCode: 'A30'
            }
          }
        })
        if (error) throw error
        if (res.code !== 0) throw new Error(res.msg)

        options.value = res.data[0] ? res.data[0].children || [] : []
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    onMounted(queryOptions)

    return () =>
      h(NTreeSelect, {
        value: props.value,
        onUpdateValue: (v) => {
          emit('updateValue', v)
          emit('update:value', v)
        },
        options: options.value,
        loading: loading.value,
        disabled: props.disabled,
        clearable: props.clearable,
        labelField: props.labelField || 'name',
        keyField: props.keyField || 'code',
        placeholder: props.placeholder || '请选择征集方式',
        multiple: props.multiple
      })
  }
})
</script>
